var _Index = null, layer = null, laypage = null, laydate = null, laytable = null, layform = null, _ajaxRun = false, _ajaxRunA = false, _ajaxRunB = false, _audio = null, _dialogLayer = null;
$(document).ready(function(){

});
$(function(){
	layui.use(['laypage','layer','laydate','form','table'], function(){
		layer = layui.layer;
		laypage = layui.laypage;
		laydate = layui.laydate;
		laytable = layui.table;
		layform = layui.form;
	});
});
//Ajax post 请求
var _Index = {
	ajax:function(url,param,callback,txt)
	{
     if(_ajaxRun) return false;
     txt = txt||'';
	 $.ajax({
	      url: url,
	      dataType:"json",
	      data:param,
	      type:'POST',
	      async:true,
	      beforeSend:function(){
		    _ajaxRun = true;
			__showLoadingBox(txt);
	      },
	      success:function(d){
	        _ajaxRun = false;
	        __hideLoadingBox();
	        if(typeof(callback) == 'function') callback(d);
	      },
	      error: function(){
		    _ajaxRun = false;
		    __hideLoadingBox();
	      }
	  });
	},
	ajaxHide:function(url,param,callback)
	{
		if(_ajaxRunA) return false;
		$.ajax({
			url: url,
			dataType:"json",
			data:param,
			type:'POST',
			async:true,
			beforeSend:function(){
				_ajaxRunA = true;
			},
			success:function(d){
				_ajaxRunA = false;
				if(typeof(callback) == 'function') callback(d);
			},
			error: function(){
				_ajaxRunA = false;
			}
		});
	},
	get:function(url,callback,txt)
	{
		if(_ajaxRunB) return false;
		txt = txt||'';
		_ajaxRunB = true;
		__showLoadingBox(txt);
		$.get(url,function(d,status){
			__hideLoadingBox();
			_ajaxRunB = false;
			if(status == 'success')
			{
				if(typeof(callback) == 'function') callback(d);
			}else{
				layer.msg('网络出错，请重试', {time: 2000,anim: 4});
			}
		});
	},
	//在微信webview打开我们h5页面的时候，就固定了页面的高度，如果这个input在页面的底部，当呼出软键盘时，由于高度问题，整个webview会被键盘顶上去，而取消时没有恢复原状
	blur:function(url,callback,txt){ 
		window.scrollTo(0, 0); 
	},
	//显示页码工具条
    setPagebar:function(_p,_limit,_total,callback){
		laypage.render({
			elem: 'layer_page_box'
			,limit: _limit
			,count: _total
			,theme: '#1E9FFF'
			,curr: _p
			, layout: ['count', 'prev', 'page', 'next', 'skip'] //'limit', 
			,jump: function(obj, first){  //obj.curr 得到当前页  obj.limit  得到每页显示的条数
				//首次不执行
				if(!first) if(typeof(callback) == 'function') callback(obj.curr);
			}
		});
		$('#layer_page_box').show();
	}, 
	//清除系统缓存
    wipecache:function(url){
		layer.confirm('您确定要清理系统缓存数据吗？', {
		    title:'清理缓存',shade:[0.4,'#000000'],btn: ['确定清理','取消'] //按钮
		}, function(){
			layer.closeAll();
			__showLoadingBox();
			$.get(url, function(d){
			    __hideLoadingBox();
			    d.msg = d.msg || '缓存已成功清理';
				layer.msg(d.msg, {time: 1000},function(){ window.location.reload(); });
				/*
				layer.alert(d.msg, { title:'成功', anim: 4, closeBtn: 0, shade:[0.4,'#000000']}, function(){ 
				    window.location.reload();
				});
				*/
			});
		});
    },
	closedialogLayer:function(l){
		l = l || _dialogLayer;
		layer.close(l);
	},
	//退出登录
    logout:function(url){
		layer.confirm('您确定要退出登录吗？', {
		    title:'退出登录',shade:[0.4,'#000000'],btn: ['确定','取消'] //按钮
		}, function(){
			layer.closeAll();
			window.location.href = url;
		});
    },
	//修改登录密码
    editLoginPwd:function(w,h){
		w = w || 500;
		h = h || 430;
		_dialogLayer = layer.open({
			title:'修改登录密码',
			type: 2,
			area: [w+'px', h+'px'],
			shade:[0.4,'#000000'],
			content: globalCfg.editAdminPwdUrl
		});
    },
	//修改手机号
    editMyMobile:function(_title,w,h){
		w = w || 500;
		h = h || 370;
		_dialogLayer = layer.open({
			title: _title || '修改手机号',
			type: 2,
			area: [w+'px', h+'px'],
			shade:[0.4,'#000000'],
			content: globalCfg.editAdminMobileUrl
		});
    },
	//修改个人资料
    editMySelf:function(w,h){
		w = w || 500;
		h = h || 340;
		_dialogLayer = layer.open({
			title:'修改个人资料',
			type: 2,
			area: [w+'px', h+'px'],
			shade:[0.4,'#000000'],
			content: globalCfg.editAdminSelfUrl
		});
    },
	//附件管理
    attachment:function(multiple,backFun,w,h){
		multiple = multiple || 0; //multiple = 0 单选，$multiple = 1 多选 
		backFun = backFun || 'selectAttachmentFun'; //选择后默认回调函数名
		w = w || 1100;
		h = h || 790;
		_dialogLayer = layer.open({
			title:'附件管理',
			type: 2,
			area: [w+'px', h+'px'],
			shade:[0.4,'#000000'],
			content: globalCfg.attachmentUrl + '?multiple=' + multiple + '&backfun=' + backFun
		});
    },
	//手机号验证
    checkPhone:function(tel){
    	var _reg = /^[1][3-9][0-9]{9}$/;
		if(_reg.test(tel)) return true;
		return false;
    },
    //播放音频
    playAudio:function(src,k){
      k = k || 0;
      var obj = $('#html_autio_' + k);
      if(obj.length > 0) obj.remove();
      $('body').append('<audio controls="controls" style="display:none" id="html_autio_'+k+'" autoplay><source src="' + src + '"/></audio>');
    },
    //excel导出
    downExcel:function(obj){
	  layer.confirm('导出需要一些时间，确定要导出吗？', {
	      title:'导出Excel',shade:[0.4,'#000000'],btn: ['确定','取消'],
	      btn1:function(){
	        layer.closeAll();
	        $(obj).submit();
	      }
	  });
    },
    //将页面Table数据导出为Excel
    saveTableToExcel:function(_ele,_name){
	  layer.confirm('导出需要一些时间，确定要导出吗？', {
	      title:'导出Excel',shade:[0.4,'#000000'],btn: ['确定','取消'],
	      btn1:function(){
	      	layer.closeAll();
	        _name = _name || new Date().getTime()+'_excel.xls';
            $.table2excel({ selector: $(_ele),filename:_name });
	      }
	  });
    },
    //对于input框只能输入数字和小数点
    bindnumber:function(obj){
	  $(obj).bind("keyup",function(){
	     $(this).val($(this).val().replace(/[^\-?\d.]/g,''));
	  });
	  $(obj).focus(function(){$(this).select();});	
    },
    //input 只能输入整数
    bindInputNum:function(obj,_val,_fun){
	  $(obj).bind("keyup",function(){
	    $(this).val($(this).val().replace(/[^\-?\d]/g,_val));
	    if(parseInt($(this).val()) <= 0)
	    {
	      $(this).val(_val);
	      layer.msg('请输入整数数值', {time: 1000}); 
	    }
		if(typeof(_fun) == 'function') _fun($(this).val());
	  });
	  $(obj).focus(function(){$(this).select();}); 
    },
    //input 只能输入整数 - 不能超最最大值
    bindInputNumTwo:function(obj,_val,_fun){
	  $(obj).bind("keyup",function(){
	    $(this).val($(this).val().replace(/[^\-?\d]/g,_val));
	    if(parseInt($(this).val()) > _val || parseInt($(this).val()) <= 0)
	    {
	      $(this).val(_val);
	      layer.msg('请输入整数数值', {time: 1000}); 
	    }
		if(typeof(_fun) == 'function') _fun($(this).val());
	  });
	  $(obj).focus(function(){$(this).select();});
    },
    //input 只能输入整数 - 不提示
    bindInputNumThree:function(obj,_val,_fun){
	  $(obj).bind("keyup",function(){
	    $(this).val($(this).val().replace(/[^\-?\d]/g,_val));
		if(typeof(_fun) == 'function') _fun($(this).val());
	  });
	  $(obj).focus(function(){$(this).select();}); 
    },
    //只能输入价格
	bindMoney:function(obj,_val,_fun){
	 $(obj).bind("keyup",function(){
	    if($(this).val() != '0.' && $(this).val() != '0.0')
	    {
	      $(this).val($(this).val().replace(/[^\-?\d.]/g,_val));
	      if(parseFloat($(this).val()) <= 0)
	      {
	        $(this).val(_val);
	        layer.msg('请输入数值', {time: 1000}); 
	      }
	    }
		if(typeof(_fun) == 'function') _fun($(this).val());
	 });
	 $(obj).focus(function(){$(this).select();}); 
	},
    //绑定回车事件
    bindEnter:function(_obj,fun)
    {
		$(_obj).bind('keypress',function(event){
		   if(event.keyCode == "13")
		   {
		      if(typeof(fun) == 'function') fun();
		   }
		});
    },
	tplDlg: function(_obj,_confimFun)
    {
		_obj = _obj || {};
		_obj.title = _obj.title || '信息';
		_obj.html = _obj.html || '';
		_obj.w = _obj.w || 500;
		_obj.h = _obj.h || 600;
		_obj.o = _obj.o || null;
		_obj.top = _obj.top || 0;
		_obj.btn = _obj.btn || ['确定','取消'];
		_obj.resize = _obj.resize || false;
		_obj.success = _obj.success || '';
		_obj.shadeClose = _obj.shadeClose || false;
		_obj.o = layer.open({
			type: 1,
			title: _obj.title,
			closeBtn: false,
			area: [_obj.w + 'px', _obj.h + 'px'],
			shadeClose:_obj.shadeClose,
			shade: ['0.4', '#000000'],
			id: 'Tpl_Dialog_A_' + Math.random(), //设定一个id，防止重复弹出
			resize: _obj.resize,
			btn: _obj.btn,
			btnAlign: 'c',
			moveType: 0, //拖拽模式，0或者1
			content: _obj.html,
			success: function(i,lo){
			  if(parseInt(_obj.top) > 0) layer.style(lo,{top: _obj.top + 'px'});
			  if(typeof(_obj.success) == 'function') _obj.success(i,lo);
			},
			cancel: function(lo){ layer.close(layero); },
			yes: function(lo,i){
			  if(typeof(_confimFun) == 'function')
			  {
				_confimFun(lo);
			  }else{
				layer.close(lo);
			  }
			},
			btn2: function(lo,i){
			  layer.close(lo);
			}
        });
	},
	promptDlg: function(_obj,_confimFun)
	{
		_obj = _obj || {};
		_obj.title = _obj.title || '请输入';
		_obj.o = _obj.o || null;
		_obj.v = _obj.v || '';
		_obj.top = _obj.top || 0;
		_obj.formType = _obj.formType || 3;
		_obj.success = _obj.success || '';
		_obj.o = layer.prompt({
			id:'tpldlg_' + Math.random(),
			title: _obj.title,
			formType: _obj.formType,
			shade: [0.4,'#000000'],
			success:function(i,o){
			  $('.layui-layer-input').val(_obj.v);
			  if(parseInt(_obj.top) > 0) layer.style(lo,{top: _obj.top + 'px'});
			  if(typeof(_obj.success) == 'function') _obj.success(i,o);
			}
		 }, function(text, index){
			 if(typeof(_confimFun) == 'function')
			 {
				_confimFun(text,index);
			 }else{
				layer.close(index);
			 }
		});
    },
	//获取form表单的所有值 - 返回 json object
	getFormJson: function(form)
	{
	    var obj = {};
	    var a = $(form).serializeArray();
	    $.each(a, function () {
			if (obj[this.name] !== undefined) {
				if (!obj[this.name].push) {
					obj[this.name] = [obj[this.name]];
				}
				obj[this.name].push(this.value || '');
			} else {
				obj[this.name] = this.value || '';
			}
	    });
	    return obj;
	},
	//将json设置form表单的值
	setFormJson: function(form,jsonObj)
	{
		if($.type(jsonObj) === "string"){  
			jsonObj = $.parseJSON(jsonObj);  
		}
		if($.isEmptyObject(jsonObj)) return false;
		var form = $(form);
		$.each(jsonObj,function(key,val){
			var formField = form.find("[name='"+key+"']");
			if($.type(formField[0]) === "undefined") return true;
			var fieldTagName = formField[0].tagName.toLowerCase();
			if(fieldTagName == "input"){  
			    if(formField.attr("type") == "radio"){  
			        $("input:radio[name='"+key+"'][value='"+val+"']").attr("checked","checked");
			    } else {  
			        formField.val(val);  
			    }  
			} else if(fieldTagName == "select"){
			    formField.val(val);  
			} else if(fieldTagName == "textarea"){
			    formField.val(val);
			} else {  
			    formField.val(val);  
			}
		});
	},
	//判断某个元素是否存在于某个 js 数组中，相当于 PHP 语言中的 in_array 函数，此函数只对字符和数字有效
	//_Index.in_array('b',new Array(['b', 2, 'a', 4])); // 判断'b'字符是否存在于 arr 数组中，存在返回true 否则false，此处将返回true
	in_array:function(v,arr)
	{
		var r = new RegExp(','+v+',');
		return (r.test(',' + arr.join(arr.S) + ','));
	}

};

//显示加载loading
function __showLoadingBox(_txt)
{
  if($('#newload-box').length > 0) $('#newload-box').empty().remove();
  _txt = _txt || '';
  var _html = '<div class="loadshade" id="newload-box">\
    <div class="load-cbox">\
        <div class="loader-02"></div>\
        <div class="lod-txt">' + _txt + '</div>\
    </div>\
  </div>';
  $('body').append(_html);
}
//隐藏加载loading
function __hideLoadingBox()
{
  if($('#newload-box').length > 0) $('#newload-box').empty().remove();
}
/**
 * 图片显示失败时
 */
function __imgErr() {
    var img = event.srcElement;
    img.src = "/static/icon_nopic.png?v=" + new Date();
    img.onerror = null;
}